<!-- 班级通讯录 -->
<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchClassContactAPI } from '@/apis/fetchClassContact'
import { useUserInfoStore } from '@/store/userInfo'
import router from '@/router'
import { useSearch } from '@/composables/search'

const userInfoStore = useUserInfoStore()

// 班级 id
const classId = ref('')

// 管理人员列表数据
const managerList = ref<Person[]>([])
// 同学录人员总数
const personTotal = ref(0)

// 同学录分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<Person>>(
  fetchContacts,
  { isNoMore: d => d?.list.length === d?.total },
)

// 搜索结果数据
const { searchText, isOpenSearch, searching, searchResult, fetchSearchResult } = useSearch<Person>(search as any, { dataKeyName: 'report_user' })

// 最终呈现的列表，如果正在搜索，就展示搜索数据
const finalList = computed(() => {
  if (isOpenSearch.value || searchText.value)
    return searchResult.value
  else
    return dataList.value
})

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onLoad((options) => {
  if (options && options.class_id) {
    classId.value = options.class_id
    refresh()
  }
  else { uni.showToast({ title: '页面加载错误：未获取到班级id', icon: 'none' }) }
})
onReachBottom(() => loadMore())

/**
 * @description 分页服务函数
 */
async function fetchContacts(d?: LoadMoreData<Person>): Promise<LoadMoreData<Person>> {
  // 缺少必要参数，先不执行
  if (!classId.value)
    return { list: [], page: 0, total: 0 }

  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchClassContactAPI({
    id: classId.value,
    page: _page.toString(),
    limit: '10',
  }, userInfoStore.userInfo!.token!)

  managerList.value = res.data?.data.manage_user || []
  personTotal.value = res.data?.data.total || 0

  return {
    list: res.data?.data.report_user || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

/**
 * @description 搜索服务函数
 */
async function search() {
  const res = await fetchClassContactAPI({
    id: classId.value,
    page: '1',
    limit: '100',
    keywords: searchText.value.length > 0 ? searchText.value : undefined,
  }, userInfoStore.userInfo!.token!)

  personTotal.value = res.data?.data.total || 0

  return res.data!
}

/**
 * @description 搜索框文本更新时触发
 */
const handleSearch = useDebounceFn((keyword: string) => {
  searchText.value = keyword
  fetchSearchResult()
}, 500)

/**
 * @description 点击“联系老师”按钮时触发
 */
function handleContactTeacher(teacherId: string, teacherName: string) {
  router.push({
    name: 'chat',
    params: {
      class_id: classId.value,
      teacher_id: teacherId,
      username: teacherName,
    },
  })
}
</script>

<template>
  <view class="bg-#F8FAFE">
    <view class="sticky left-0 top-0 z-50 bg-white">
      <Spacer height="48" />
      <uv-search
        bg-color="#F3F3F3"
        placeholder="请输入人员姓名/电话查询"
        search-icon-size="52rpx"
        color="#333333"
        placeholder-color="#A7A7A7"
        height="80rpx"
        margin="0 25rpx"
        :show-action="false"
        @change="handleSearch"
        @focus="isOpenSearch = true"
        @blur="isOpenSearch = false"
      />
      <Spacer height="15" />
    </view>
    <view v-if="managerList.length > 0" class="bg-white py-20rpx">
      <view class="mx-25rpx text-24rpx text-#333333 leading-32rpx">
        教师和工作人员({{ managerList.length }})
      </view>
      <Spacer height="6" />
      <PersonItem
        v-for="manager in managerList"
        :key="manager.id"
        :avatar="manager.avatar || ''"
        :name="manager.username"
        :position="manager.duties"
      >
        <button
          class="flex items-center justify-center rounded-full bg-#0037AE px-20rpx py-14rpx text-24rpx text-white font-semibold leading-32rpx"
          hover-class="bg-#3266D9"
          @tap="handleContactTeacher(manager.id.toString(), manager.username)"
        >
          联系老师
        </button>
      </PersonItem>
    </view>
    <Spacer height="20" />
    <view class="relative min-h-80vh bg-white py-20rpx">
      <view class="mx-25rpx text-24rpx text-#333333 leading-32rpx">
        同学录({{ personTotal }})
      </view>
      <Spacer height="6" />
      <PersonItem
        v-for="person in finalList"
        :key="person.id"
        :avatar="person.avatar || ''"
        :name="person.username"
        :position="person.duties"
      />
      <!-- 加载更多 -->
      <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
      <PageDefault v-if="finalList.length === 0">
        暂无联系人
      </PageDefault>
    </view>
  </view>
  <uv-loading-page :loading="(loading && !loadingMore) || searching" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'contacts'
style:
  navigationBarTitleText: '通讯录'
layout: 'custom'
</route>
